#!/bin/bash
# Reinstall Script - Modified for Debian 12.5.0

### 注释掉Windows部分配置 ###
# WINDOWS_ISO="http://jdc.cool/d/Yd/WIN10_LSTC_TVNC(1).iso"
# PARTITION_SCHEME_WINDOWS="autopart --type=msdos"
# WINDOWS_BOOTLOADER="--boot-drive=/dev/sda --force-extra-removable"

### Debian 配置区 (已解除注释) ###
DEBIAN_ISO="https://cdimage.debian.org/cdimage/archive/12.5.0/amd64/iso-dvd/debian-12.5.0-amd64-DVD-1.iso"
DEBIAN_MIRROR="http://mirrors.tuna.tsinghua.edu.cn/debian/"
PARTITION_SCHEME_DEBIAN="auto --disk=/dev/vda --root=ext4"
DEBIAN_PRESEED="
d-i debian-installer/locale string en_US.UTF-8
d-i console-keymaps-at/keymap select us
d-i netcfg/choose_interface select auto
d-i netcfg/get_hostname string debian
d-i netcfg/get_domain string local
d-i mirror/country string CN
d-i mirror/http/hostname string mirrors.tuna.tsinghua.edu.cn
d-i mirror/http/directory string /debian
d-i mirror/http/proxy string
"

### 通用参数 (保持原样) ###
TARGET_DISK="/dev/vda"
TIMEZONE="Asia/Shanghai"
KEYBOARD_LAYOUT="us"
NETWORK_INTERFACE="eth0"
SSH_PORT="22"

### 安装流程控制 ###
prepare_environment() {
    # 卸载Windows相关模块
    # rmmod ntfs 2>/dev/null || true
    # 加载Debian所需驱动
    modprobe virtio_blk
    modprobe virtio_net
}

download_iso() {
    wget --no-check-certificate -O /tmp/debian.iso "$DEBIAN_ISO"
    mount -o loop /tmp/debian.iso /mnt
}

configure_grub() {
    cat > /boot/grub/grub.cfg <<EOF
menuentry 'Debian Installer' {
    insmod part_msdos
    insmod ext2
    set root=(hd0,msdos1)
    linux /vmlinuz preseed/file=/preseed.cfg
    initrd /initrd.gz
}
EOF
}

generate_preseed() {
    cat > /preseed.cfg <<EOF
$DEBIAN_PRESEED
d-i partman-auto/disk string $TARGET_DISK
d-i partman-auto/method string regular
d-i partman-auto/choose_recipe select $PARTITION_SCHEME_DEBIAN
d-i clock-setup/utc boolean true
d-i time/zone string $TIMEZONE
d-i finish-install/reboot_in_progress note
EOF
}

start_installation() {
    debconf-set-selections /preseed.cfg
    apt-install debian-installer-launcher
    anna-install debian-installer-utils
    tasksel install standard
}

### 主执行流程 ###
prepare_environment
download_iso
generate_preseed
configure_grub
start_installation

echo "Debian 12.5.0安装配置已完成，请重启系统" >&2